<script setup>

/**
 * 商品列表
 */
import { ref, toRefs, onMounted, onUnmounted } from "vue";
import { store, loginOpen } from '@/js/store.js';
import { debounce, diy_api } from '@/js/api.js';

import { ElMessage } from 'element-plus'

// 自定义组件名称，保持与缓存名一致可被缓存
defineOptions({ name: 'product-list' });

const props = defineProps({
    hashName: String,
    xuanze: Boolean,
    initObj: Object,
});


const rowsData = ref([]);
const listMeta = ref({ page: 1, total: 1, per_page: 10 })
const search_source = ()=> {return {}}
const search = ref(search_source());

const form = ref({})
const dialog = ref(false)
const dialogTitle = ref('')

//需要响应式时使用toRefs
const { initObj } = toRefs(props);


//向父级传递消息
const emits = defineEmits(['tohost'])
function sindEmit(msg) {
    emits('tohost', msg);
}

function onPage(url) {
    location.hash = '#' + url
}

function getList(_page) {
    if (_page) {
        listMeta.value.page = _page;
    }
    diy_api.get({ page: listMeta.value.page, ...search.value }).then((res) => {
        var result = res.data;
        if (result.state) {
            rowsData.value = result.data;
            // listMeta.value = result.meta;
        }
    }).catch((err) => {
        console.log("🚀 ~ product_api.get ~ err:", err)
    })
}
getList()




onMounted(() => {
})
onUnmounted(() => {
})

const method = ref("add");
function rowsAdd() {
    method.value = "add";
    dialogTitle.value = "添加"
    form.value = {};
    dialog.value = true;
}
function rowsEdit(row, _forbid) {
    method.value = "edit";
    dialogTitle.value = '修改';
    form.value = JSON.parse(JSON.stringify(row));
    dialog.value = true;
}

// 删除
function delData(id) {
    product_api.del(id).then((res) => {
        var result = res.data;
        if (result.code == 200) {
            getList()
            ElMessage({ message: result.message || "删除成功", type: 'success' })
        } else {
            ElMessage({ message: result.message || "删除失败！", type: 'error' })
        }
    })

}

const multipleSelection = ref([])
function handleSelectionChange(val) {
    multipleSelection.value = val
}
function seleDel() {
    if (multipleSelection.value.length == 0) {
        ElMessage.error({ message: '请选择删除项！' })
        return;
    }
    var id = multipleSelection.value.map(e => e.id)
    delData(id)
}

const rules = ref({
    name: [
        { required: true, message: '不能为空！', trigger: 'blur', },
        { min: 2, message: '不能少于2个字符', trigger: 'blur', },
    ],
})



//------------------------检索
// 搜索
function souSubmit() {
    getList(1);
}



// responseType: 'blob' 下载文件
async function onDowntemp() {
    try {
        const res = await product_api.downtemp()
        var result = res.data;
        const contentDisposition = res.headers['content-disposition'] || res.headers['Content-Disposition'];
        var filename = exportName(contentDisposition);
        const url = window.URL.createObjectURL(new Blob([result]))
        // const url = window.URL.createObjectURL(base64ToBlob(result))
        onDownFile({ name: filename || '商品模板.xls', url: url })
        ElMessage({ message: result.message || "导出成功", type: 'success' })
    } catch (error) {
        let reader = new FileReader()
        reader.readAsText(error.response.data)
        reader.onload = function () {
            const json = JSON.parse(reader.result)
            ElMessage({ message: json.message || "导出失败！", type: 'error' })
        }
    }
}


</script>

<template>

    <div style="width: 100%;">

        <el-card body-style="padding:10px" style="width: 100%; margin: 5px auto;">
            <div class="toolscon">

                <el-popconfirm v-if="!xuanze" :title="'确定删除' + multipleSelection.length + '条数据？'" icon-color="red" @confirm="seleDel()">
                    <template #reference>
                        <el-button type="danger" plain>批量删除</el-button>
                    </template>
                </el-popconfirm>
                <el-button v-if="!xuanze" type="warning" plain @click="rowsAdd()">添加</el-button>
                <el-input v-model="search.name" placeholder="请输入检索名称" @keyup.enter.native="souSubmit" clearable
                    style="width: 200px;"></el-input>
                <el-button type="primary" plain @click="souSubmit">查询</el-button>

            </div>
        </el-card>

        <el-table ref="multipleTable" class="mytable" :data="rowsData" size="default" style="width: 100%"
            @selection-change="handleSelectionChange" stripe>
            <el-table-column v-if="!xuanze" type="selection" width="55" fixed></el-table-column>
            <el-table-column label="商品" width="220" fixed>
                <template #default="scope">
                    <div class="flexrow" style="width: 210px;">
                        <div style="width: 60px;height: 60px;overflow: hidden;border-radius: 6px;">
                            <img class="handle objcover" :src="scope.row.thumbnail">
                        </div>
                        <div style="width: 140px;">
                            <div class="ellipsis">{{ scope.row.name }}</div>
                            <div class="ellipsis" style="color: #999;font-size: 12px">{{ scope.row.categoryName }}</div>
                        </div>
                        <div style="color: #bbb;font-size: 12px;">{{ scope.row.bar_code }}</div>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="200" v-if="!xuanze">
                <template #default="scope">

                    <a @click="rowsEdit(scope.row)">修改</a>
                    <el-popconfirm title="确定删除?" icon-color="red" @confirm="delData(scope.row.id)">
                        <template #reference>
                            <a><span style="color: var(--el-color-danger)">删除</span></a>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="200" v-if="xuanze">
                <template #default="scope">
                    <el-button type="warning" @click="sindEmit(scope.row)" :disabled="initObj?.selected?.find(ev=>ev.id==scope.row.id)?true:false">选择</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- <div class="pagination">
            <el-pagination background layout="total, prev, pager, next" :current-page="listMeta.page"
                :total="listMeta.total" :page-size="listMeta.per_page" class="right"
                @current-change="getList"></el-pagination>
            <hr>
        </div> -->

    </div>


</template>

<style scoped>
.toolscon{margin: 0;}
.toolscon >*{margin: 3px;}
</style>